import {
    ScreenSpaceEventHandler,
    Event,
    Cartesian3,
    CallbackProperty,
    Color,
    DistanceDisplayCondition,
    NearFarScalar,
    VerticalOrigin,
    LabelStyle,
    ScreenSpaceEventType,
    Cartesian2,
    Math as CesiumMath,
    PolylineDashMaterialProperty,
    Cartographic,
    PolygonHierarchy,
    HorizontalOrigin,
    HeightReference
} from 'cesium';
import * as turf from '@turf/turf';
import deleteImage from '@/assets/images/delete.png';

class CesiumMeasureArea {
    constructor(viewer) {
        this.viewer = viewer;
        this.initEvents();
        this.positions = [];
        this.tempPositions = [];
        this.vertexEntities = [];
        this.labelEntity = undefined;
        this.measureArea = 0; //测量结果
        this.deleteButtonEntities = []; // 添加删除按钮实体数组
        this.currentMeasureGroupId = null; // 添加测量组ID
        this.allPolygonEntities = []; // 添加多边形实体数组
        // 添加删除按钮的点击事件处理器
        this.clickHandler = new ScreenSpaceEventHandler(this.viewer.scene.canvas);
        this.clickHandler.setInputAction(this.handleEntityClick.bind(this), ScreenSpaceEventType.LEFT_CLICK);
    }

    //初始化事件
    initEvents() {
        this.handler = new ScreenSpaceEventHandler(this.viewer.scene.canvas);
        this.MeasureStartEvent = new Event(); //开始事件
        this.MeasureEndEvent = new Event(); //结束事件
    }

    //激活
    activate() {
        this.deactivate();
        this.registerEvents(); //注册鼠标事件
        //设置鼠标状态
        this.viewer.enableCursorStyle = false;
        this.viewer.scene.canvas.style.cursor = 'default';
        this.isMeasure = true;
        this.measureArea = 0;
        this.currentMeasureGroupId = Date.now().toString(); // 生成新的测量组ID
        this.MeasureStartEvent.raiseEvent(); // 触发开始事件
    }

    //禁用
    deactivate() {
        if (!this.isMeasure) return;
        this.unRegisterEvents();
        this.viewer.scene.canvas.style.cursor = 'pointer';
        this.viewer.enableCursorStyle = true;
        this.isMeasure = false;
        this.tempPositions = [];
        this.positions = [];
        this.height = undefined;
    }

    //清空绘制
    clear() {
        // 清除所有多边形实体
    this.allPolygonEntities.forEach(entity => {
        this.viewer.entities.remove(entity);
    });
    this.allPolygonEntities = [];
    this.polygonEntity = undefined;

        this.vertexEntities.forEach(item => {
            this.viewer.entities.remove(item);
        });
        this.vertexEntities = [];

        this.viewer.entities.remove(this.mesureResultEntity);
        this.mesureResultEntity = undefined;

        // 清除删除按钮
        this.deleteButtonEntities.forEach(entity => {
            this.viewer.entities.remove(entity);
        });
        this.deleteButtonEntities = [];

        this.height = undefined;
    }


    // 创建面对象
    createPolygonEntity() {
        this.polygonEntity = this.viewer.entities.add({
            polygon: {
                hierarchy: new CallbackProperty(e => {
                    return new PolygonHierarchy(this.tempPositions);
                }, false),
                material: Color.RED.withAlpha(0.4),
                perPositionHeight: true,
            },
            polyline: {
                positions: new CallbackProperty(e => {
                    return this.tempPositions.concat(this.tempPositions[0]);
                }, false),
                width: 1,
                material: new PolylineDashMaterialProperty({
                    color: Color.YELLOW,
                }),
                depthFailMaterial: new PolylineDashMaterialProperty({
                    color: Color.YELLOW,
                }),
            },
            measureGroupId: this.currentMeasureGroupId // 添加测量组ID
        });

        this.createResultLabel();
    }

    //创建节点
    createVertex() {
        let vertexEntity = this.viewer.entities.add({
            position: this.positions[this.positions.length - 1],
            type: "MeasureAreaVertex",
            point: {
                color: Color.FUCHSIA,
                pixelSize: 8,
                disableDepthTestDistance: 500,
            },
            isMeasureVertex: true,
            measureGroupId: this.currentMeasureGroupId // 添加测量组ID
        });
        this.vertexEntities.push(vertexEntity);
    }


    // 测量结果标签
    createResultLabel() {
        this.mesureResultEntity = this.viewer.entities.add({
            position: new CallbackProperty(e => {
                return this.getCenterPosition()
            }, false),
            type: "MeasureAreaResult",
            label: {
                text: new CallbackProperty(e => {
                    if (this.tempPositions.length < 3) return "";
                    return "面积" + this.computeArea(this.tempPositions) + "平方米";
                }, false),
                scale: 0.5,
                font: 'normal 28px MicroSoft YaHei',
                distanceDisplayCondition: new DistanceDisplayCondition(0, 5000),
                scaleByDistance: new NearFarScalar(1000, 1, 3000, 0.4),
                verticalOrigin: VerticalOrigin.BOTTOM,
                style: LabelStyle.FILL_AND_OUTLINE,
                pixelOffset: new Cartesian2(0, -30),
                outlineWidth: 9,
                outlineColor: Color.YELLOW
            },
            measureGroupId: this.currentMeasureGroupId // 添加测量组ID
        });
    }

    //获取节点的中心点
    getCenterPosition() {
        let points = [];
        if (this.tempPositions.length < 3) return this.tempPositions[0];
        this.tempPositions.forEach(position => {
            const point3d = this.cartesian3ToPoint3D(position);
            points.push([point3d.x, point3d.y]);
        })

        //构建turf.js  lineString
        let geo = turf.lineString(points);
        let bbox = turf.bbox(geo);
        let bboxPolygon = turf.bboxPolygon(bbox);
        let pointOnFeature = turf.center(bboxPolygon);
        let lonLat = pointOnFeature.geometry.coordinates;

        return Cartesian3.fromDegrees(lonLat[0], lonLat[1], this.height + 0.3);
    }


    //注册鼠标事件
    registerEvents() {
        this.leftClickEvent();
        this.rightClickEvent();
        this.mouseMoveEvent();
    }

    //左键点击事件
    leftClickEvent() {
        //单击鼠标左键画点点击事件
        this.handler.setInputAction(e => {
            this.viewer.scene.canvas.style.cursor = 'default';
            let position = this.viewer.scene.pickPosition(e.position);
            if (!position) {
                const ellipsoid = this.viewer.scene.globe.ellipsoid;
                position = this.viewer.scene.camera.pickEllipsoid(e.position, ellipsoid);
            }
            if (!position) return;
            this.positions.push(position);
            this.height = this.unifiedHeight(this.positions, this.height);
            if (this.positions.length === 1) { //首次点击
                this.createPolygonEntity();
            }
            this.createVertex();

        }, ScreenSpaceEventType.LEFT_CLICK);
    }

    //鼠标移动事件
    mouseMoveEvent() {
        this.handler.setInputAction(e => {
            if (!this.isMeasure) return;
            this.viewer.scene.canvas.style.cursor = 'default';
            let position = this.viewer.scene.pickPosition(e.endPosition);
            if (!position) {
                position = this.viewer.scene.camera.pickEllipsoid(e.startPosition, this.viewer.scene.globe.ellipsoid);
            }
            if (!position) return;
            this.handleMoveEvent(position);
        }, ScreenSpaceEventType.MOUSE_MOVE);
    }

    // 处理鼠标移动
    handleMoveEvent(position) {
        if (this.positions.length < 1) return;

        this.height = this.unifiedHeight(this.positions, this.height);
        this.tempPositions = this.positions.concat(position);

        // 更新当前多边形的面积标签
        if (this.tempPositions.length >= 3 && this.mesureResultEntity) {
            this.mesureResultEntity.position = this.getCenterPosition();
            this.mesureResultEntity.label.text = "面积" + this.computeArea(this.tempPositions) + "平方米";
        }
    }

    //统一节点的高度
    unifiedHeight(positions, height) {
        if (!height) height = this.getPositionHeight(positions[0]); //如果没有指定高度 就用第一个的高度
        let point3d;
        for (let i = 0; i < positions.length; i++) {
            const element = positions[i];
            point3d = this.cartesian3ToPoint3D(element);
            positions[i] = Cartesian3.fromDegrees(point3d.x, point3d.y, height)
        }

        return height;
    }

    //获取某个点的高度
    getPositionHeight(position) {
        const cartographic = Cartographic.fromCartesian(position);
        return cartographic.height;
    }

    cartesian3ToPoint3D(position) {
        const cartographic = Cartographic.fromCartesian(position);
        const lon = CesiumMath.toDegrees(cartographic.longitude);
        const lat = CesiumMath.toDegrees(cartographic.latitude);
        return { x: lon, y: lat, z: cartographic.height };
    }


    // 添加创建删除按钮方法
    createDeleteButton(position, measureGroupId) {
        const deleteButton = this.viewer.entities.add({
            position: position,
            billboard: {
                image: deleteImage,
                scale: 0.05,
                horizontalOrigin: HorizontalOrigin.CENTER,
                verticalOrigin: VerticalOrigin.CENTER,
                scaleByDistance: new NearFarScalar(300, 1, 1200, 0.4),
                distanceDisplayCondition: new DistanceDisplayCondition(0, 10000),
                pixelOffset: new Cartesian2(0, 30)
            },
            isDeleteButton: true,
            measureGroupId: measureGroupId
        });

        this.deleteButtonEntities.push(deleteButton);
        return deleteButton;
    }

    // 添加实体点击处理方法
    handleEntityClick(click) {
        if (this.isMeasure) return;

        const pickedObject = this.viewer.scene.pick(click.position);
        if (pickedObject && pickedObject.id && pickedObject.id.isDeleteButton) {
            const measureGroupId = pickedObject.id.measureGroupId;
            this.deleteMeasureGroup(measureGroupId);
        }
    }

    // 添加删除测量组方法
    deleteMeasureGroup(measureGroupId) {
        // 删除多边形实体
        const polygonToRemove = this.allPolygonEntities.find(entity => entity.measureGroupId === measureGroupId);
        if (polygonToRemove) {
            this.viewer.entities.remove(polygonToRemove);
            this.allPolygonEntities = this.allPolygonEntities.filter(entity => entity.measureGroupId !== measureGroupId);
        }
    
        // 删除顶点实体
        const verticesToRemove = this.vertexEntities.filter(entity => entity.measureGroupId === measureGroupId);
        verticesToRemove.forEach(entity => {
            this.viewer.entities.remove(entity);
        });
        this.vertexEntities = this.vertexEntities.filter(entity => entity.measureGroupId !== measureGroupId);
    
        // 删除结果标签
        const labelToRemove = this.viewer.entities.values.find(
            entity => entity.type === "MeasureAreaResult" && entity.measureGroupId === measureGroupId
        );
        if (labelToRemove) {
            this.viewer.entities.remove(labelToRemove);
        }
    
        // 删除删除按钮
        const buttonToRemove = this.deleteButtonEntities.find(entity => entity.measureGroupId === measureGroupId);
        if (buttonToRemove) {
            this.viewer.entities.remove(buttonToRemove);
            this.deleteButtonEntities = this.deleteButtonEntities.filter(entity => entity.measureGroupId !== measureGroupId);
        }
    }

    // 右键事件
    rightClickEvent() {
        this.handler.setInputAction(e => {
            if (!this.isMeasure || this.positions.length < 3) {
                this.deactivate();
                this.clear();
            } else {
                this.tempPositions = [...this.positions];
                
                // 保存当前的多边形实体
                if (this.polygonEntity) {
                    this.allPolygonEntities.push(this.polygonEntity);
                }
    
                // 更新多边形属性
                this.polygonEntity.polyline = {
                    positions: this.positions.concat(this.positions[0]),
                    width: 2,
                    material: Color.YELLOW,
                    depthFailMaterial: new PolylineDashMaterialProperty({
                        color: Color.YELLOW,
                    }),
                };

                // 计算面积并更新 measureArea 属性
            this.measureArea = this.computeArea(this.positions);
            
    
                this.polygonEntity.polygon.hierarchy = new PolygonHierarchy(this.tempPositions);
                this.mesureResultEntity.position = this.getCenterPosition();
                this.mesureResultEntity.label.text = "总面积" + this.computeArea(this.positions) + "平方米";
    
                // 添加删除按钮
                const centerPosition = this.getCenterPosition();
                this.createDeleteButton(centerPosition, this.currentMeasureGroupId);
    
                this.measureEnd();
            }
        }, ScreenSpaceEventType.RIGHT_CLICK);
    }


    //测量结束
    measureEnd() {
        this.deactivate();
        this.MeasureEndEvent.raiseEvent(this.measureArea); //触发结束事件 传入结果
    }

    //解除鼠标事件
    unRegisterEvents() {
        this.handler.removeInputAction(ScreenSpaceEventType.RIGHT_CLICK);
        this.handler.removeInputAction(ScreenSpaceEventType.LEFT_CLICK);
        this.handler.removeInputAction(ScreenSpaceEventType.MOUSE_MOVE);
    }

    // 计算多边形面积
    computeArea(positions) {
        let points = [];
        positions.forEach(position => {
            const point3d = this.cartesian3ToPoint3D(position);
            points.push([point3d.x, point3d.y]);
        });
        // 确保多边形是封闭的
        points.push(points[0]);
        const polygon = turf.polygon([points]);
        return turf.area(polygon);
    }
}

export default CesiumMeasureArea;
